package com.guchenbo.lssp.template;

import com.guchenbo.lssp.core.Statement;
import com.guchenbo.lssp.domain.LivyStatementOutputQo;
import com.guchenbo.lssp.exception.SessionException;
import com.guchenbo.lssp.pool.PooledSession;
import com.guchenbo.lssp.pool.SessionSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author guchenbo
 */
public class LsspTemplate {
    protected static final Logger log = LoggerFactory.getLogger(LsspTemplate.class);

    private SessionSource sessionSource;

    public LsspTemplate(SessionSource sessionSource) {
        this.sessionSource = sessionSource;
    }

    /**
     * 执行sql，不处理返回
     *
     * @param sql sql
     * @throws SessionException sql错误直接抛错
     */
    public void execute(String sql) throws SessionException {
        executeQuery(sql, dataJson -> null);
    }

    /**
     * 执行sql，sql错误直接抛错
     *
     * @param sql              sql
     * @param dataJsonCallback 处理返回结果
     * @param <T>              范型
     * @return 回调处理结果
     * @throws SessionException sql错误直接抛错
     */
    public <T> T executeQuery(String sql, OutputDataJsonCallback<T> dataJsonCallback) throws SessionException {
        PooledSession session = null;
        Statement statement;
        try {
            session = sessionSource.getSession();
            log.info("get session {}", session.getId());
            statement = session.createStatement(sql);
        } finally {
            closeQuietly(session);
        }
        log.info("create statement success {}", statement.getId());
        LivyStatementOutputQo.OutputDataJson dataJson = statement.executeQuery();
        return dataJsonCallback.process(dataJson);
    }

    private void closeQuietly(PooledSession session) {
        if (session != null) {
            session.close();
        }
    }
}
